package com.letu.core.utils;

import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 自定义手动校验器
 * @ClassName ValidateUtil
 * @Description TODO
 * @Author liuxiaobai
 * @Date 2021/8/26 11:20 上午
 * @Version 1.0
 */
public class ValidateUtil {

    private static final Validator VALIDATOR;

    static {
        //使用hibernate的注解来进行验证 failFast true仅仅返回第一条错误信息 false返回所有错误
        VALIDATOR = Validation.byProvider(HibernateValidator.class).configure().buildValidatorFactory().getValidator();

    }
    /**
     * bean手动校验-值返回true/false
     * @param obj 校验的对象
     * @param groupClasses 规则分组集合
     * @return 校验通过-true 校验失败-false
     */
    public static<T> Boolean validateSimple(T obj, Class<?>... groupClasses) {
        return validate(obj,groupClasses).isEmpty();
    }
    /**
     * bean手动校验
     * @param obj 校验的对象
     * @param groupClasses 规则分组集合
     * @return 校验失败的错误信息
     */
    public static<T> Set<ConstraintViolation<T>> validate(T obj, Class<?>... groupClasses) {
        Set<ConstraintViolation<T>> constraintViolations;
        if (groupClasses != null && groupClasses.length > 0) {
            constraintViolations = VALIDATOR.validate(obj, groupClasses);
        } else {
            constraintViolations = VALIDATOR.validate(obj);
        }
        return constraintViolations;
    }

}
